/*
 * @Description: CryptoUtil
 * @Author: zhaokun
 * @Date: 2022-01-07 15:39:01
 * @LastEditTime: 2022-01-15 12:23:40
 * @FilePath: \user\common\nwCrypto.go
 */
package common

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/hmac"
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
	"io"

	// "github.com/mfpierre/go-mcrypt"
	"golang.org/x/crypto/bcrypt"
)

const NW_KEY_16 = "niuwa123456789ab"
const NW_KEY_32 = "niuwa123456789abba987654321awuin"

type CryptoUtil interface {
	Md5(str string) string
	Sha1(str string) string
	Sha256(str string) string
	Sha512(str string) string
	Hash(str string) string
	CompareHash(str string, compareStr string) bool
	Aes16(str string) string
	AesDeCrypt16(str string) string
	// Aes32(str string) string        //需开启gcc
	// AesDeCrypt32(str string) string //需开启gcc
	Base64Encode(str string) string
	Base64Decode(str string) string
	Hmac(str string) string
}

type nwCryptoUtil struct {
}

func NewNwCryptoUtil() *nwCryptoUtil {
	return &nwCryptoUtil{}
}

/**
 * @description: md5
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Md5(str string) string {
	data := []byte(str)
	has := md5.Sum(data)
	md5str := fmt.Sprintf("%x", has) //将[]byte转成16进制
	return md5str
}

/**
 * @description: Sha1
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Sha1(str string) string {
	data := []byte(str)
	has := sha1.Sum(data)
	shastr := fmt.Sprintf("%x", has) //将[]byte转成16进制
	return shastr
}

/**
 * @description: Sha256
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Sha256(str string) string {
	w := sha256.New()
	io.WriteString(w, str) //将str写入到w中
	bw := w.Sum(nil)       //w.Sum(nil)将w的hash转成[]byte格式

	shastr := hex.EncodeToString(bw) //将 bw 转成字符串
	return shastr
}

/**
 * @description: Sha512
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Sha512(str string) string {
	w := sha512.New()
	io.WriteString(w, str) //将str写入到w中
	bw := w.Sum(nil)       //w.Sum(nil)将w的hash转成[]byte格式

	shastr := hex.EncodeToString(bw) //将 bw 转成字符串
	return shastr
}

/**
 * @description: Hash
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Hash(str string) string {
	strHash, err := bcrypt.GenerateFromPassword([]byte(str), bcrypt.DefaultCost)
	if err != nil {
		return ""
	}
	return string(strHash)
}

/**
 * @description: CompareHash
 * @param {string} str
 * @param {string} compareStr
 * @return bool
 */
func (crypto *nwCryptoUtil) CompareHash(str string, compareStr string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(str), []byte(compareStr))
	if err != nil {
		return false
	}
	return true
}

/**
 * @description: Aes16
 * @param {string} str
 * @return string
 */

func (crypto *nwCryptoUtil) Aes16(str string) string {
	origData := []byte(str)
	key := []byte(NW_KEY_16)
	//创建加密算法实例
	block, err := aes.NewCipher(key)
	if err != nil {
		return ""
	}
	//获取块的大小
	blockSize := block.BlockSize()
	//对数据进行填充，让数据长度满足需求
	origData = pkcs7Padding(origData, blockSize)
	//采用AES加密方法中CBC加密模式
	blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	//执行加密
	blocMode.CryptBlocks(crypted, origData)
	return string(crypted)

}

/**
 * @description: AesDeCrypt16
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) AesDeCrypt16(str string) string {
	//创建加密算法实例
	cypted := []byte(str)
	key := []byte(NW_KEY_16)
	block, err := aes.NewCipher(key)
	if err != nil {
		return ""
	}
	//获取块大小
	blockSize := block.BlockSize()
	//创建加密客户端实例
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(cypted))
	//这个函数也可以用来解密
	blockMode.CryptBlocks(origData, cypted)
	//去除填充字符串
	origData, err = pkcs7UnPadding(origData)
	if err != nil {
		return ""
	}
	return string(origData)
}

/**
 * @description: Aes32
 * @param {string} str
 * @return string
 */
// func (crypto *nwCryptoUtil) Aes32(str string) string {
// 	// using CAST-256 in ECB mode
// 	key := []byte(NW_KEY_32)
// 	plaintext := []byte(str)
// 	iv := make([]byte, 16)
// 	encrypted, err := mcrypt.Encrypt(key, iv, plaintext, "cast-256", "ecb")
// 	if err != nil {
// 		return ""
// 	}
// 	return string(encrypted)
// }

/**
 * @description: AesDeCrypt32
 * @param {string} str
 * @return string
 */
// func (crypto *nwCryptoUtil) AesDeCrypt32(str string) string {
// 	encrypted := []byte(str)
// 	key := []byte(NW_KEY_32)
// 	iv := make([]byte, 16)
// 	decrypted, err := mcrypt.Decrypt(key, iv, encrypted, "cast-256", "ecb")
// 	if err != nil {
// 		return ""
// 	}
// 	return string(decrypted)
// }

/**
 * @description: Base64Encode
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Base64Encode(str string) string {
	return base64.StdEncoding.EncodeToString([]byte(str))
}

/**
 * @description:Base64Decode
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Base64Decode(str string) string {
	decodeBytes, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		return ""
	}
	return string(decodeBytes)
}

/**
 * @description: Base64Encode
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) UrlEncode(str string) string {
	return base64.URLEncoding.EncodeToString([]byte(str))
}

/**
 * @description:Base64Decode
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) UrlDecode(str string) string {
	urldecode, err := base64.URLEncoding.DecodeString(str)
	if err != nil {
		return ""
	}
	return string(urldecode)
}

/**
 * @description: Hmac
 * @param {string} str
 * @return string
 */
func (crypto *nwCryptoUtil) Hmac(str string) string {
	hmac := hmac.New(md5.New, []byte(NW_KEY_32))
	hmac.Write([]byte(str))
	return hex.EncodeToString(hmac.Sum([]byte("")))
}

//PKCS7 填充模式
func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	//Repeat()函数的功能是把切片[]byte{byte(padding)}复制padding个，然后合并成新的字节切片返回
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

//填充的反向操作，删除填充字符串
func pkcs7UnPadding(origData []byte) ([]byte, error) {
	//获取数据长度
	length := len(origData)
	if length == 0 {
		return nil, errors.New("加密字符串错误！")
	} else {
		//获取填充字符串长度
		unpadding := int(origData[length-1])
		//截取切片，删除填充字节，并且返回明文
		return origData[:(length - unpadding)], nil
	}
}
